package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@WebFilter("/demo")
public class FilterDemo01 implements Filter {
    //        1. 在filter成员位置定义阈值变量 ：`private static final int MAX_COUNT = 5;`
    private static final int MAX_COUNT = 5;
    //        2. 在filter成员位置定义计数器：`private AtomicInteger filterCount = new AtomicInteger(0);`
    private AtomicInteger filterCount = new AtomicInteger(0);
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //书写代码

//        3. doFilter()方法实现步骤
//                判断计数器中计数是否大于阈值
        if (filterCount.get() > MAX_COUNT){
            //   * 是：请求转发到 `index.jsp` 排队页面

            request.getRequestDispatcher("index.jsp").forward(request, response);
        }else {
//        * 否：完成以下步骤

//        1. 计数器加一
            //获取当前的值并加1
            filterCount.getAndAdd(1);
        }

//        2. 放行
        chain.doFilter(request, response);
//        3. 计数器减一
        //获取当前的值并自减
        filterCount.getAndDecrement();
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}